<template>
  <div>
    <!--:model="shop" 数据双向绑定-->
    <!--ref="shopForm" id="shopForm",给form去一个名字-->
    <!--:rules="formRules" 校验规则-->
    <el-form :model="shop" ref="shopForm" :rules="formRules" label-position="left" label-width="100px" class="demo-ruleForm login-container">
      <h3 class="title">店铺入驻</h3>
      <el-form-item prop="name"label="名称">
        <el-input type="text" v-model="shop.name" auto-complete="off" placeholder="请输入店铺名称！"></el-input>
      </el-form-item>
      <el-form-item prop="tel" label="座机">
        <el-input type="text" v-model="shop.tel" auto-complete="off" placeholder="请输入座机！"></el-input>
      </el-form-item>
      <el-form-item prop="address" label="店铺地址">
        <el-input type="text" v-model="shop.address" auto-complete="off" placeholder="请输入地址！"></el-input>
                <el-button size="small" type="primary" @click="selectAdrress">选择</el-button>
      </el-form-item>
      <el-form-item prop="logo" label="店铺Logo">
        <el-upload
            class="upload-demo"
            action="http://localhost:8080/fastdfs"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          <span slot="tip" class="el-upload__tip" style="color: #e64242" v-text="tishi"></span>
        </el-upload>
      </el-form-item>
      <h3 class="title">管理员信息设置</h3>
      <el-form-item prop="admin.username" label="账号">
        <el-input type="text" v-model="shop.admin.username" auto-complete="off" placeholder="请输入账号！"></el-input>
      </el-form-item>
      <el-form-item prop="" label="图片验证码">
        <el-input type="text" v-model="imageCodeValue" style="width: 280px;" auto-complete="off" placeholder="请输入图片验证码"></el-input>
        <img @click="getImageCode" :src="imageCode"  class="captcha-image-temp"  alt="点击换图" title="点击换图" style="vertical-align: middle; cursor: pointer;">

      </el-form-item>
      <el-form-item prop="admin.phone" label="手机号码">
        <el-input type="text" v-model="shop.admin.phone" auto-complete="off" placeholder="请输入电话！"></el-input>
      </el-form-item>
       <el-form-item prop="" label="手机验证码">
        <el-input type="text" v-model="phoneRegisterForm.phoneCode"  style="width: 280px;"  auto-complete="off" placeholder="请输入手机验证码！"></el-input>
         <el-button class="btn" @click="sendPhoneCode" :disabled="isLockPhone" id="sendPhoneCode">获取</el-button>
      </el-form-item>
      <el-form-item prop="admin.email" label="电子邮件">
        <el-input type="text" v-model="shop.admin.email" auto-complete="off" placeholder="请输入邮件！"></el-input>
      </el-form-item>
      <el-form-item prop="" label="邮箱验证码">
        <el-input type="text" v-model="emailRegisterForm.emailCode"  style="width: 280px;"  auto-complete="off" placeholder="请输入邮箱验证码！"></el-input>
        <el-button class="btn" @click="sendEmailCode($event)" :disabled="isLockEmail" id="sendEmailCode">获取</el-button>
      </el-form-item>
      <el-form-item prop="admin.password" label="密码">
        <el-input type="password" v-model="shop.admin.password" auto-complete="off" placeholder="请输入密码！"></el-input>
      </el-form-item>
      <el-form-item prop="admin.comfirmPassword" label="确认密码">
        <el-input type="password" v-model="shop.admin.comfirmPassword" auto-complete="off" placeholder="请输入确认密码！"></el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click.native.prevent="settledIn" >入驻</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
        title="选择地址"
        :visible.sync="dialogVisable"
        width="30%">
      <baidu-map :center="{lng: 116.403765, lat: 39.914850}" :zoom="11">
        <bm-view class="map"></bm-view>
        <bm-control :offset="{width: '10px', height: '10px'}">
          <!--:sugStyle="{zIndex: 2100} 让搜索提示上浮-->
          <bm-auto-complete v-model="keyword" :sugStyle="{zIndex: 2100}">
            <div style="margin-bottom:10px">
              <input id="searchInput" type="text" placeholder="请输入关键字" class="searchinput"/>
              <el-button type="success" @click="selectAdrressConfirm">确定</el-button>
            </div>
          </bm-auto-complete>
        </bm-control>
        <bm-local-search :keyword="keyword" :auto-viewport="true" ></bm-local-search>
      </baidu-map>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisable=false">取 消</el-button>
        <el-button type="primary" @click="dialogVisable=false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.shop.admin.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      keyword:'',
      tishi:'',
      dialogVisable:false,
      fileList: [],
      imageCodePrefix:'data:image/jpeg;base64,',
      imageCode:'',
      imageCodeValue: '',
      //shop:shop 为了做数据表单校验不要嵌套对象
      shop: {
        name: '',
        tel: '',
        address: '',
        logo:'',
        admin:{
          username:"",
          phone:"17711345926",
          email:"1247780087@qq.com",
          password:"",
          comfirmPassword:""
        }
      },
      isLockEmail: false,
      isLockPhone: false,
      shopRegister:{},
      phoneRegisterForm:{
        phone:'',
        imageCodeValue:'',
        imageCodeKey:'',
        phoneCode:'',
        type:null
      },
      emailRegisterForm:{
        email:'',
        imageCodeValue:'',
        imageCodeKey:'',
        emailCode:'',
        type:null
      },
      formRules: {
        name: [
          { required: true, message: '请输入店铺名称!', trigger: 'blur' }
        ],
        imageCodeValue: [
          { required: true, message: '请输入图形验证码!', trigger: 'blur' }
        ],
        phoneCode: [
          { required: true, message: '请输入手机验证码!', trigger: 'blur' }
        ],
        emailCode: [
          { required: true, message: '请输入邮箱验证码!', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入店铺座机!', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入店铺地址!', trigger: 'blur' }
        ],
        'admin.phone': [
          { required: true, message: '请输入手机号!', trigger: 'blur' }
        ],
        logo: [
            { required: true, message: '请输入店铺logo!', trigger: 'blur' }
        ],
        'admin.email': [
          { type: 'email',required: true, message: '请输入邮箱!', trigger: 'blur' }
        ],
        'admin.username': [
          { required: true, message: '请输入账号!', trigger: 'blur' }
        ],
        'admin.password': [
          { required: true, message: '请输入密码!', trigger: 'blur' }
        ],
        'admin.comfirmPassword': [
          {required: true,validator: validatePass2, trigger: 'blur' } //自定义校验规则
        ]
      }
    };
  },
  methods: {
    selectAdrressConfirm(){
      //获取值搜索框值,设置给地址
      var searchInputV=document.getElementById("searchInput").value;
      this.shop.address = searchInputV;
      //关闭对话框
      this.dialogVisable = false;
    },
    selectAdrress(){
      this.dialogVisable = true;
    },
    //文件上传成功回调
    handleSuccess(response, file, fileList){
      this.shop.logo = response.resultObj;
      let para = Object.assign({}, this.shop);
      this.$http.post("/baiduAudit/imgCensor", para)
        .then(result=>{
          var isCompliance = JSON.parse(result.data.resultObj);
          console.log(isCompliance);
          if(isCompliance.conclusionType != 1){
            var filePath =file.response.resultObj;
            // 不合规则 删除该图片
            this.$http.delete("/fastdfs?filePath="+filePath)
                .then(res=>{})
            // 提示语
            this.tishi = "logo" + isCompliance.data[0].msg + "，请从新上传！";
            this.$message({
              message: this.tishi,
              type: 'error'
            });
          }else{
            this.tishi = '';
            this.$message({
              message: 'logo可以使用！',
              type: 'success'
            });
          }
        })
    },
    //文件删除
    handleRemove(file, fileList) {
      this.tishi = '';
      var filePath =file.response.resultObj;
      this.$http.delete("/fastdfs?filePath="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    //图片预览
    handlePreview(file) {
      console.log(file);
    },
    //提交入驻
    settledIn(){
      if(this.tishi){
        this.$message({
          message: this.tishi,
          type: 'error'
        });
      }else{
        this.$refs.shopForm.validate((valid) => {
          //校验表单成功后才做一下操作
          if (valid) {
            this.$confirm('确认入驻吗？', '提示', {}).then(() => {
              this.shopRegister.shop = this.shop;
              this.shopRegister.phoneCode = this.phoneRegisterForm.phoneCode;
              this.shopRegister.emailCode = this.emailRegisterForm.emailCode;
              //拷贝后面对象的值到新对象,防止后面代码改动引起模型变化
              let para = Object.assign({}, this.shopRegister); //shop 本身这个参数里面就有店铺和管理员信息
              // 为了后台好接收，封装一个对象放到里面
              this.$http.post("/shop/settlement",para).then((res) => {
                if(res.data.success){
                  this.$message({
                    message: '操作成功!',
                    type: 'success'
                  });
                  //重置表单
                  this.$refs['shopForm'].resetFields();
                  //跳转登录页面
                  this.$router.push({ path: '/login' });
                }
                else{
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

              });
            });
          }
        })
      }
    },
    // 1.生成UUID的方法
    createUuid(){
      var s = [];
      var hexDigits = "0123456789abcdefghi";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },
    getImageCode(){
      // 2.1.从localStorage中获取UUID
      let imageCodeKey = sessionStorage.getItem("shopRegisterImageCodeKey");
      // 2.2.判断当前浏览器本地是否有key值，没有则生成，有则直接使用
      if(!imageCodeKey || imageCodeKey === ''){
        imageCodeKey = this.createUuid();
        sessionStorage.setItem("shopRegisterImageCodeKey",imageCodeKey);
      }
      console.log(imageCodeKey);
      // 2.3.发送Axios请求，传递UUID，得到图形验证码的Base64字符串
      this.$http.get("/verifyCode/image/"+imageCodeKey).then(res=>{
        // 2.3.1.将接口返回的图形验证码Base64字符串码+前缀赋值给模型中的imageCode字段
        this.imageCode = this.imageCodePrefix+res.data.resultObj;
      })
    },
    sendPhoneCode(event){
      var sendBtn = event.currentTarget;
      this.isLockPhone = true;

      // 4.给图形验证码RedisKey赋值
      this.phoneRegisterForm.imageCodeKey = sessionStorage.getItem("shopRegisterImageCodeKey");
      this.phoneRegisterForm.phone = this.shop.admin.phone;
      this.phoneRegisterForm.imageCodeValue = this.imageCodeValue;
      this.phoneRegisterForm.type = 0;
      //5.发送ajax请求
      this.$http.post("/verifyCode/smsCode",this.phoneRegisterForm).then(res=>{
        var ajaxResult = res.data;
        if(ajaxResult.success){
          this.$message({
            message: "验证码已经发送到您的手机，验证码有效期为：3分钟",
            type: 'success'
          });
          //5.1.发送成：倒计时
          var time = 10;
          var interval = window.setInterval( function () {
            //每一条倒计时减一
            time = time - 1 ;

            //把倒计时时间搞到按钮上
            sendBtn.innerHTML = time+"秒后重发";

            //5.2.倒计时完成恢复按钮
            if(time <= 0){
              sendBtn.innerHTML = "重新发送";
              //清除定时器
              window.clearInterval(interval);
              this.isLockPhone = false;
            }
          },1000);
        }else{
          //5.3.发送失败：提示，恢复按钮
          this.isLockPhone = false;
          this.$message({
            message: ajaxResult.message,
            type: 'error'
          });
        }
      })

    },
    sendEmailCode(event){
      var sendBtn = event.currentTarget;
      this.isLockEmail = true;

      // 4.给图形验证码RedisKey赋值
      this.emailRegisterForm.imageCodeKey = sessionStorage.getItem("shopRegisterImageCodeKey");
      this.emailRegisterForm.email = this.shop.admin.email;
      this.emailRegisterForm.imageCodeValue = this.imageCodeValue;
      this.emailRegisterForm.type = 0;
      //5.发送ajax请求
      this.$http.post("/verifyCode/emailCode",this.emailRegisterForm).then(res=>{
        var ajaxResult = res.data;
        if(ajaxResult.success){
          this.$message({
            message: "验证码已经发送到您的邮箱，验证码有效期为：5分钟",
            type: 'success'
          });
          //5.1.发送成：倒计时
          var time = 60;
          var interval = window.setInterval( function () {
            //每一条倒计时减一
            time = time - 1 ;

            //把倒计时时间搞到按钮上
            sendBtn.innerHTML = time+"秒后重发";

            //5.2.倒计时完成恢复按钮
            if(time <= 0){
              this.isLockEmail = false;
              sendBtn.innerHTML = "重新发送";
              //清除定时器
              window.clearInterval(interval);
            }
          },1000);
        }else{
          //5.3.发送失败：提示，恢复按钮
          this.isLockEmail = false;
          this.$message({
            message: ajaxResult.message,
            type: 'error'
          });
        }
      })
    }
  },
  mounted() {
    this.getImageCode();
  }
}

</script>
<style lang="scss" scoped>
.login-container {
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-border-radius: 5px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 500px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }
  .remember {
    margin: 0px 0px 35px 0px;
  }
}

.map {
  width: 100%;
  height: 300px;
}
.searchinput{
  width: 300px;
  box-sizing: border-box;
  padding: 9px;
  border: 1px solid #dddee1;
  line-height: 20px;
  font-size: 16px;
  height: 38px;
  color: #333;
  position: relative;
  border-radius: 4px;
}
</style>